package com.rtline.business.handler;

import java.util.Map;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;

import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;

/**
 * <p>CustomSheetWriteHandler .
 *
 *
 * <p>change history:
 *
 * <pre>
 * date         defect       person          comments
 * --------------------------------------------------------------------------------
 * 2025/6/6    ********     Tao Ren    create file.
 * </pre>
 *
 * @author Tao Ren
 * @date 2025/6/6 15:35
 */

public class CustomSheetWriteHandler implements SheetWriteHandler {
    private final Map<Integer, String[]> dropdownOptions;

    public CustomSheetWriteHandler(Map<Integer, String[]> dropdownOptions) {
        this.dropdownOptions = dropdownOptions;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Sheet sheet = writeSheetHolder.getSheet();
        DataValidationHelper validationHelper = sheet.getDataValidationHelper();

        dropdownOptions.forEach((columnIndex, options) -> {
            DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(options);
            CellRangeAddressList addressList = new CellRangeAddressList(0, 10000, columnIndex, columnIndex); // 假设下拉框范围是第1行到第100行
            DataValidation validation = validationHelper.createValidation(constraint, addressList);
            // 设置数据验证的显示和提示信息
            validation.setShowPromptBox(true);
            validation.setShowErrorBox(true);
            validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
            validation.createErrorBox("错误", "请从下拉列表中选择一个选项！");
            sheet.addValidationData(validation);
        });
    }

    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheet writeSheet) {
        // No action needed
    }
}